#include "glwidget.h"

GLWidget::GLWidget(QWidget *parent)
    : QOpenGLWidget(parent), lineContext(nullptr)
{
    this->setAttribute(Qt::WA_AlwaysStackOnTop);
}

GLWidget::~GLWidget()
{

}

void GLWidget::resizeWidget()
{
    QWidget *parent = this->parentWidget();
    if(parent) {
        qDebug() << this->width() << this->height() << "before";
        this->setGeometry(0, 0, parent->width(), parent->height());
        this->resizeGL(this->width(), this->height());
        qDebug() << this->width() << this->height() << "after";
    }
}

void GLWidget::initializeGL()
{
    initializeOpenGLFunctions();
    backProgram = new GLBackgroundProgram(":/Shader/Shader/normalV.vsh", ":/Shader/Shader/fragShader.fsh", this);
    backProgram->setLocation();
    backProgram->bind();
    int temp = backProgram->getLocation("pos");
    backProgram->setAttributeArray(temp, backProgram->getBackgroundVertexData(), 2);
    temp = backProgram->getLocation("currentColor");
    backProgram->setUniformValue(temp, QVector4D(1.0, 1.0, 0.0, 1.0));
    backProgram->release();

    scanProgram = new glscanprogram(":/Shader/Shader/normalV.vsh", ":/Shader/Shader/fragShader.fsh", this);
    scanProgram->setLocation();
    scanProgram->bind();
    temp = scanProgram->getLocation("pos");
    scanProgram->setAttributeArray(temp, scanProgram->getScanVertexData(), 2);
    temp = scanProgram->getLocation("currentColor");
    scanProgram->setUniformValue(temp, QVector4D(1.0, 1.0, 0.0, 1.0));
    scanProgram->release();
}

void GLWidget::paintGL()
{
    QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
    f->glViewport(0, 0, this->width(), this->height());
    f->glClearColor(0.0, 0.0, 0.0, 1.0);
    f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    backProgram->bind();
    int pos = backProgram->getLocation("pos");
    int size = backProgram->getBackgroundVertexSize();
    backProgram->setAttributeArray(pos, backProgram->getBackgroundVertexData(), 2);
    backProgram->enableAttributeArray(pos);
    f->glDrawArrays(GL_POINTS, 0, size);
    backProgram->disableAttributeArray(pos);
    backProgram->release();

    scanProgram->bind();
    pos = scanProgram->getLocation("pos");
    scanProgram->setAttributeArray(pos, scanProgram->getScanVertexData(), 2);
    size = scanProgram->getScanVertexSize();
    scanProgram->enableAttributeArray(pos);
    f->glDrawArrays(GL_LINE_STRIP, 0, size);
    scanProgram->disableAttributeArray(pos);
    scanProgram->release();
    emit renderDone();
}

void GLWidget::resizeGL(int w, int h)
{
    QOpenGLFunctions *f = this->context()->functions();
    f->glViewport(0, 0, w, h);
}

void GLWidget::renderNow()
{
    this->update();
}
